<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>地皮内容</h3>
      <el-form ref="dataForm" :rules="rules" :model="lease" label-width="150px">
        <el-form-item label="视频地址(hls)" prop="monitorUrl">
          <el-input v-model="lease.monitorUrl" placeholder="例：http://hls01open.ys7.com/openlive/c521bfa1fe7447249545335c816b2858.m3u8" />
        </el-form-item>
        <el-form-item label="视频地址(.live)" prop="ezvizUrl">
          <el-input v-model="lease.ezvizUrl" placeholder="例：ezopen://open.ys7.com/E14190806/1.hd.live" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="lease.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="lease.intro" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="所属分区" prop="categoryId">
          <el-select v-model="lease.categoryId" placeholder="选择所属分区">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="默认图片" prop="defaultImageUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handledefaultimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeDefaultUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="defaultLoading" class="preimg" />
            <div v-show="lease.defaultImageUrl" :style="'background-image:url('+lease.defaultImageUrl+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="lease.defaultImageUrl" type="hidden" class="hidden-input" />
        </el-form-item>
        <el-form-item label="展示图片" prop="imageUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeAvatarUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="loading" class="preimg" />
            <div v-show="lease.imageUrl" :style="'background-image:url('+lease.imageUrl+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="lease.imageUrl" type="hidden" class="hidden-input" />
        </el-form-item>
        <el-form-item label="地址" prop="city">
          <area-select v-model="selectedAddr" :data="pca" type="text" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="lease.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="水分（%）" prop="moisture">
          <el-input v-model="lease.moisture" type="number" placeholder="请输入水分" />
        </el-form-item>
        <el-form-item label="光照（lux）" prop="illumination">
          <el-input v-model="lease.illumination" type="number" placeholder="请输入光照" />
        </el-form-item>
        <el-form-item label="温度（℃）" prop="temp">
          <el-input v-model="lease.temp" type="number" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="二氧化碳（ppm）" prop="co2">
          <el-input v-model="lease.co2" type="number" placeholder="请输入二氧化碳" />
        </el-form-item>
        <el-form-item v-if="seedArr.length > 0" label="种子" prop="ids" >
          <el-checkbox-group v-model="seedList">
            <el-checkbox v-for="item in seedArr" :label="item.id" :key="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="内容" prop="text">
          <editor :init="editorInit" v-model="lease.text" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="!lease.id" type="primary" @click="handleCreate">保存内容</el-button>
      <el-button v-if="lease.id" type="primary" @click="handleEdit">更新内容</el-button>
    </div>
  </div>
</template>

<style>
  .hidden-input{
    display: block;
    width:0px;
    height:0px;
  }
  .el-upload--picture{
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
  }
  .el-upload-list--picture{
    display: none;
  }
  .upload-img .preimg{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
  }
  .el-loading-spinner{
    top:0;
  }
</style>

<script>
import { editLease, createLease, detailLease } from '@/api/lease'
import { selectCategory } from '@/api/leaseCategory'
import { selectSeed } from '@/api/seed'
import { uploadPath, createStorage } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import { pca } from 'area-data'
import 'vue-area-linkage/dist/index.css'

export default {
  name: 'LeaseAdd',
  components: { Editor },
  data() {
    return {
      leaseId: '',
      uploadPath,
      lease: {
        imageUrl: '', address: '', city: ''
      },
      selectedAddr: [],
      typeList: [],
      pca: pca,
      loading: false,
      defaultLoading: false,
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '简介不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '所属分区不能为空', trigger: 'blur' }
        ],
        defaultImageUrl: [
          { required: true, message: '默认图片不能为空', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '展示图片不能为空', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        text: [
          { required: true, message: '新闻内容不能为空', trigger: 'blur' }
        ]
      },
      seedList: [],
      seedArr: [],
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        width: 600,
        height: 400,
        content_style: 'img {width:100%;height:auto;} p {margin:16px 0 0;font-size: 12px;color: #666666;text-align: justify;line-height: 20px;}',
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }

    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  watch: {
    selectedAddr(n) {
      this.lease.province = n[0]
      this.lease.city = n[1]
    },
    seedList(n) {
      this.lease.ids = n.join(',')
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      const leaseId = this.$route.query.id
      selectCategory()
        .then(response => {
          this.typeList = response.data.data
        })
        .catch(() => {})
      selectSeed()
        .then(response => {
          this.seedArr = response.data.data
        })
        .catch(() => {})
      if (leaseId) {
        detailLease(leaseId).then(response => {
          this.lease = Object.assign({}, response.data.data)
          if (this.lease.ids) {
            const arr = []
            const idsArr = this.lease.ids.split(',')
            idsArr.forEach(item => {
              item = parseInt(item)
              arr.push(item)
            })
            this.seedList = arr
          }
          this.selectedAddr = [this.lease.province, this.lease.city]
        })
      }
    },
    handleCancel: function() {
      this.$router.push({ path: '/home/leaselist' })
    },
    handleCreate: function() {
      this.formValidate(1)
    },
    handleEdit: function() {
      this.formValidate(2)
    },
    formValidate: function(type) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalCont = {
            ...this.lease
          }
          if (type === 1) {
            createLease(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/home/leaselist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          } else if (type === 2) {
            editLease(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/home/leaselist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.lease.imageUrl = response.url
        this.loading = false
      }
    },
    handleErrorimgsUrl(response, file, fileList) {
      this.$notify.error({
        title: '失败',
        message: '请重新上传图片'
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.loading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.loading = false
      }
      return isLt2M
    },
    handledefaultimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.lease.defaultImageUrl = response.url
        this.defaultLoading = false
      }
    },
    beforeDefaultUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.defaultLoading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.defaultLoading = false
      }
      return isLt2M
    }

  }
}
</script>
